#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>

//用户私钥
const char *uid = "4e78c607dbbc9f4d6b5c16ffa5622fb7";

//订阅主题
const char *topic = "test";

//删除字符串结尾的换行符
void trim(char* s)
{
  s[strcspn(s, "\r\n")] = 0;
}

//读取一行，遇到换行符停止
ssize_t readline(int fd, void *vptr, size_t maxlen) {
  ssize_t n, rc;
  char c, *ptr;

  ptr = vptr;
  for (n = 1; n < maxlen; n++) {
    if ((rc = read(fd, &c, 1)) == 1) {
      *ptr++ = c;
      if (c == '\n')
        break;
    } else if (rc == 0) {
      *ptr = 0;
      return (n - 1);
    } else {
      return -1;
    }
  }

  *ptr = 0;
  return n;
}

//写入N个字节，处理短写
ssize_t writen(int fd, const void *vptr, size_t n) {
  size_t nleft = n;
  ssize_t nwritten;
  const char *ptr = vptr;

  while (nleft > 0) {
    if ((nwritten = write(fd, ptr, nleft)) <= 0) {
        return -1;
    }

    nleft -= nwritten;
    ptr += nwritten;
  }

  return n;
}

//写入字符串并增加换行符
ssize_t writeline(int fd, char *line) {
  size_t bytes = 0;
  bytes += writen(fd, line, strlen(line));
  bytes += writen(fd, "\r\n", 2);
  printf("< %s\n", line);
  return bytes;
}

//处理收到的消息
void process(int sfd, char *msg) {
  char *p = NULL;
  printf("> %s\n", msg);
  while ((p = strsep(&msg, "&"))) {
    printf("parameter: %s\n", p);
    //遍历消息中的参数
    char *key = NULL;
    char *val = p;
    //解析键值对
    key = strsep(&val, "=");
    printf("key: %s\n", key);
    printf("value: %s\n", val);
  }
}

int main() {
  int sfd;
  fd_set fds;
  struct timeval tv = {0, 0};
  struct sockaddr_in addr;
  char msg[BUFSIZ];

  //忽略SIGPIPE信号
  signal(SIGPIPE, SIG_IGN);

  sfd = socket(PF_INET, SOCK_STREAM, 0);
  if (sfd < 0) {
    perror("socket");
    return 1;
  }

  printf("connecting bemfa.com\n");

  //连接TCP创客云
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = inet_addr("119.91.109.180");
  addr.sin_port = htons(8344);
  if (connect(sfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in))) {
    perror("connect");
    return 1;
  }

  printf("server connected\n");

  //订阅主题，可以一次订阅多个主题
  sprintf(msg, "cmd=1&uid=%s&topic=%s", uid, topic);
  writeline(sfd, msg);

  printf("topic %s subscribed\n", topic);

  while (1) {
    FD_ZERO(&fds);
    FD_SET(sfd, &fds);

    //如果上一次循环没有超时，继续计时
    if (tv.tv_sec == 0)
    {
      //每60秒发送一次心跳
      tv.tv_sec = 60;
      tv.tv_usec = 0;
    }

    //等待服务器下发命令
    int ret = select(sfd + 1, &fds, NULL, NULL, &tv);
    //出错
    if (ret < 0) {
      perror("select");
      continue;
    }
    //超时发送心跳
    if (ret == 0) {
      writeline(sfd, "ping");
      continue;
    }
    //检查socket是否可读
    if (!FD_ISSET(sfd, &fds)) {
      continue;
    }
    //接收消息
    readline(sfd, msg, sizeof(msg));
    trim(msg);
    //处理消息
    process(sfd, msg);
  }

  close(sfd);

  return 0;
}
